/*
 * @Description:
 * @Autor: HuiSir<273250950@qq.com>
 * @Date: 2024-02-08 12:56:45
 * @LastEditTime: 2024-09-03 00:46:06
 */
import { ref } from "../utils/vue.esm.js"
import Request from "./api/request.js"
const template = /*html*/ `
  <button v-if="showBtn" type="button" @click="loadMore">
    {{loading?'正在加载...':'加载更多'}}
  </button>
`

function getNextPostsPageLink () {
  return document.getElementById('nextPostsPageLink')
}

export default {
  template,
  setup () {
    const loading = ref(false)
    const showBtn = ref(!!getNextPostsPageLink()?.value)

    const loadMore = () => {
      loading.value = true
      const nextPostsPageLink = getNextPostsPageLink()?.value
      if (nextPostsPageLink) {
        Request.get(nextPostsPageLink).then(pageXml => {
          const placeholder = document.createElement('div')
          placeholder.innerHTML = pageXml
          const $articles = placeholder.querySelector('#Posts')?.children
          showBtn.value = !!$articles
          if (!$articles) return
          document.querySelector('#Posts').append(...Array.from($articles))
          const newPostsPageLink = placeholder.querySelector('#nextPostsPageLink')?.value //找出新的下一页链接
          getNextPostsPageLink().value = newPostsPageLink || ''
        }).finally(() => {
          loading.value = false
        })
      }
    }

    return { loading, loadMore, showBtn }
  },
}
